import 'lib_draw_text_platform_interface.dart';

class LibDrawText {
  //单例
  static LibDrawText? _instance;
  static LibDrawText get instance => _instance ??= LibDrawText._();
  LibDrawText._();


  static const List<int> byteList = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01];

  static List<int> getByteList() {
    return byteList;
  }

  Future<String?> getPlatformVersion() {
    return LibDrawTextPlatform.instance.getPlatformVersion();
  }

  //设置字体文件路径
  Future<void> setFontFilePath(String path) async{
    await LibDrawTextPlatform.instance.invokeMethod("setFontFilePath", path);
  }

  ///  绘制文字点阵
  Future<List<int>> drawText(String char, int width, int height, int textHeight) async {
    var bytes = [];
    if (char == " ") {
      bytes = List.filled(height * 8, 0);
    } else {
      var data = await LibDrawTextPlatform.instance
          .invokeMethod("drawText", {"width": width, "height": height, "text": char, "textHeight": textHeight});
      if (data != null) {
        bytes = data["data"];
      }
    }

    if (bytes.isNotEmpty) {
      var b = bytes;
      List<int> list = [];
      int count = 0;
      int index = 0;
      for (int i = 0; i < b.length; i++) {
        if (index != 0 && index % 8 == 0) {
          list.add(count);
          count = 0;
        } else if (i != 0 && i % height == 0) {
          list.add(count);
          count = 0;
          index = 0;
        }
        int tmpNum = b[i];
        if (tmpNum == 1) {
          count = count | byteList[index % byteList.length];
        }
        index++;
      }
      list.add(count);

      //处理两个字相连的问题
      //除以8,然后向上取整
      int c = (height / 8.0).ceil();
      bool isWhite = false;
      for (int i = 0; i < c; i++) {
        int tmp = list[list.length - 1 - i];
        if (tmp != 0) {
          isWhite = true;
          break;
        }
      }

      if (isWhite) {
        for (int i = 0; i < c; i++) {
          list.add(0);
        }
      }

      return list;
    } else {
      return [];
    }
  }
}
